import React, { useState, useEffect } from "react";
import {
  Button,
  Spin,
  Modal,
  Input,
  message,
  Popconfirm,
  Pagination,
} from "antd";
import { _list, _changepwd, _delete } from "./Api";
import "./User_data.css";

const User_data = (props) => {
  const [users, setUsers] = useState([]); // 初始化状态来存储用户数据
  const [loading, setLoading] = useState(true); // 初始化加载状态
  const [current, setCurrent] = useState(1); //当前页
  const [isModalOpen, setIsModalOpen] = useState(false); //初始化提示框
  const [password, setPassword] = useState(""); // 存储用户输入的密码
  const [id, setId] = useState(""); // 存储修改密码用户的id

  //列表数据渲染
  useEffect(() => {
    //列表请求
    const Usersreq = async () => {
      try {
        const res = await _list([1, 10]);
        // 从服务器返回的数据中提取用户列表
        const usersList = await res[0];
        // 将获取到的用户数据和加载状态设置到状态中
        setUsers(usersList);
        setLoading(false);
      } catch (err) {
        console.error("Error:", err);
        setLoading(false);
      }
    };
    //调用列表请求
    Usersreq();
  }, []);

  // 如果还在加载，显示加载状态
  if (loading) {
    return <Spin />;
  }

  //列表翻页
  const onchange = async (cur) => {
    //设置当前页state
    setCurrent(cur);
    //重新渲染列表数据
    const res = await _list([cur, 10]);
    const usersList = res[0];
    setUsers(usersList);
  };

  //修改密码模态框
  const showModal = (e) => {
    setId(e.id);
    setIsModalOpen(true);
  };
  //确认新密码
  const handleOk = async () => {
    await _changepwd({
      id: `${id}`,
      modifiedpassword: `${password}`,
    });
    //重新渲染列表数据
    const res = await _list([current, 10]);
    const usersList = res[0];
    setUsers(usersList);
    setIsModalOpen(false); // 关闭模态框
  };
  //取消修改密码
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //删除账号确认框
  const confirm = async (e) => {
    await _delete(e.id);
    message.success("删除成功");
    const res = await _list([current, 10]);
    const usersList = res[0];
    setUsers(usersList);
  };
  const cancel = () => {
    message.error("取消删除");
  };

  return (
    <>
      <h1>用户列表</h1>
      <p>用户信息展示，可进行用户密码修改和删除用户操作</p>
      <table border="1" cellSpacing="0">
        <thead>
          <tr>
            <th>账号</th>
            <th>密码</th>
            <th>姓名</th>
            <th>性别</th>
            <th>电话</th>
            <th>地址</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {users.map((item) => (
            <tr key={item.id}>
              <td>{item.account}</td>
              <td>{item.password}</td>
              <td>{item.name}</td>
              <td>{item.sex}</td>
              <td>{item.phone}</td>
              <td>{item.address}</td>
              <td>
                <Button onClick={() => showModal(item)}>修改密码</Button>

                <Popconfirm
                  title="删除："
                  description="确认删除此账号吗？"
                  onConfirm={() => confirm(item)}
                  onCancel={cancel}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button danger>删除账号</Button>
                </Popconfirm>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <Pagination
        align="end"
        onChange={(current) => onchange(current)}
        defaultCurrent={1}
        total={30}
        className="pages"
      />

      {/* 修改密码模态框 */}
      <Modal
        title="请输入新密码："
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Input value={password} onChange={(e) => setPassword(e.target.value)} />
      </Modal>
    </>
  );
};

export default User_data;
